﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;

using Beyondbit.Desktop.Common;
using RBS.Common;
using RBS.Common.JsonEntity;
using RBS.Core.Model;
using RBS.Web.Hotel.Controllers;
using RBS.Web.Hotel.Models.Dine;
using Webdiyer.WebControls.Mvc;

using RBS.Core.Extension;
using UIModel = RBS.Web.Hotel.Models;
using RBS.Web.Hotel.Service;

namespace RBS.Web.Hotel.Areas.Settlement.Controllers
{
    public class DineController : BaseController
    {
        private DineService _dineService;

        #region Ctors

        public DineController() {
            _dineService = new DineService();
        }

        #endregion 
        #region 订单列表

        public ActionResult OrderList(Int32 pageIndex = 1)
        {
            UIModel.Dine.OrderQueryCondition condition = new UIModel.Dine.OrderQueryCondition()
            {
                PageIndex = pageIndex,
                HotelId = CurrentUser.HotelId,
                PageSize = 10,
                OrderField = "Id desc"
            };

            Int32 recordCount = 0;
            IList<UIModel.Dine.OrderViewModel> list = _dineService.QueryOrderList(condition, out recordCount);
            PagedList<UIModel.Dine.OrderViewModel> pageList = new PagedList<UIModel.Dine.OrderViewModel>(list, condition.PageIndex, condition.PageSize, recordCount);

            if (Request.IsAjaxRequest())
                return PartialView("_OrderList", pageList);

            return View(pageList);

            //IList<UIModel.Dine.OrderViewModel> list = new List<UIModel.Dine.OrderViewModel>();
            //PagedList<UIModel.Dine.OrderViewModel> pageList = new PagedList<UIModel.Dine.OrderViewModel>(list, 1, 10, 0);
            //return View(pageList);
        }

        [HttpPost]
        public ActionResult OrderList(String orderId,String orderUser,String orderMobile,String beginDate,String endDate,String orderState,String orderChannel,Int32 pageIndex=1 ) {

            Int32 recordCount = 0;
            UIModel.Dine.OrderQueryCondition condition = new UIModel.Dine.OrderQueryCondition()
            {
                PageIndex = pageIndex,
                HotelId = CurrentUser.HotelId,
                PageSize = 10,
                OrderField = "Id desc",
                OrderId = orderId,
                ContactUser = orderUser,
                ContactMobile = orderMobile,
                BeginDate = beginDate,
                EndDate = beginDate,
                OrderState = orderState,
                OrderChannel = orderChannel
            };

            IList<UIModel.Dine.OrderViewModel> list = _dineService.QueryOrderList(condition, out recordCount);

            PagedList<UIModel.Dine.OrderViewModel> pageList = new PagedList<UIModel.Dine.OrderViewModel>(list, condition.PageIndex, condition.PageSize, recordCount);


            return View("_OrderList", pageList);
        }

        #endregion 
        #region 订单详细

        /// <summary>
        /// 订单详细
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderDetail(Int32 id) {

            var orderModel = _dineService.GetOrder(id, true); 
            var operateRecord = _dineService.QueryOrderOpeateRecord(id); 
            ViewBag.OperateList = operateRecord;

            var orderComment = _dineService.QueryOrderComment(id).FirstOrDefault();
            ViewBag.orderComment = orderComment;


           /* var operateRecord = new RBS.Core.BLL.D_OperateRecord().GetModelList(" orderId=" + id);
            ViewBag.operateRecord = operateRecord;*/

            return View(orderModel);

        }

        #endregion 
        #region 订单确认

        /// <summary>
        /// 订单确认
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ConfirmOrder(String orderId) {
            var ret = new JsonReturnMessages();
            ret.IsSuccess = false;
            ret.Msg = "未知错误";
            try
            {
                Int32 orderId_int = 0;
                if (Int32.TryParse(orderId, out orderId_int))
                {
                    Boolean result = _dineService.ConfirmOrder(orderId_int);
                    if (result)
                    {
                        ret.IsSuccess = true;
                        ret.Msg = "订单确认成功";
                    }
                    else {
                        ret.IsSuccess = false;
                        ret.Msg = "订单确认失败";
                    }
                }
                else {
                    throw new Exception(String.Format("无效的订单ID：{0}", orderId));
                }          
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = String.Format("操作失败！{0}", exception.Message);
                return Json(ret);
            }

            return Json(ret);
        }


        public ActionResult OrderConfirmation(Int32 orderId)
        {
            var orderDetailList = new RBS.Core.BLL.D_Order_Details().GetModelList(String.Format(" OrderId='{0}' ", orderId));

            return View(orderDetailList);
        }

        #endregion 
        #region 订单取消

        /// <summary>
        /// 订单取消
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CancelOrder(String orderId)
        {
            var ret = new JsonReturnMessages();
            ret.IsSuccess = false;
            ret.Msg = "未知错误";
            try
            {
                Int32 orderId_int = 0;
                if (Int32.TryParse(orderId, out orderId_int))
                {
                    Boolean result = _dineService.CancelOrder(orderId_int);
                    if (result)
                    {
                        ret.IsSuccess = true;
                        ret.Msg = "订单取消成功";
                    }
                    else
                    {
                        ret.IsSuccess = false;
                        ret.Msg = "订单取消失败，当前订单状态无法再取消！";
                    }
                }
                else
                {
                    throw new Exception(String.Format("无效的订单ID：{0}", orderId));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = String.Format("操作失败！{0}", exception.Message);
                return Json(ret);
            }

            return Json(ret);
        }

        #endregion 
        #region 订单结帐

        /// <summary>
        /// 订单结帐
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult CheckoutOrder(String orderId)
        {
            var ret = new JsonReturnMessages();
            ret.IsSuccess = false;
            ret.Msg = "未知错误";
            try
            {
                Int32 orderId_int = 0;
                if (Int32.TryParse(orderId, out orderId_int))
                {
                    Boolean result = _dineService.CheckOutOrder(orderId_int);
                    if (result)
                    {
                        ret.IsSuccess = true;
                        ret.Msg = "订单结帐成功";
                    }
                    else
                    {
                        ret.IsSuccess = false;
                        ret.Msg = "订单结帐失败";
                    }
                }
                else
                {
                    throw new Exception(String.Format("无效的订单ID：{0}", orderId));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = String.Format("操作失败！{0}", exception.Message);
                return Json(ret);
            }

            return Json(ret);
        }

        #endregion 
        #region CheckinOrder 就坐
        [HttpPost]
        public ActionResult CheckinOrder(String orderId)
        {
            var ret = new JsonReturnMessages {IsSuccess = false, Msg = "未知错误"};
            try
            {
                Int32 orderId_int = 0;
                if (Int32.TryParse(orderId, out orderId_int))
                {
                    Boolean result = _dineService.CheckinOrder(orderId_int);
                    if (result)
                    {
                        ret.IsSuccess = true;
                        ret.Msg = "就坐成功";
                    }
                    else
                    {
                        ret.IsSuccess = false;
                        ret.Msg = "就坐失败";
                    }
                }
                else
                {
                    throw new Exception(String.Format("无效的订单ID：{0}", orderId));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = String.Format("操作失败！{0}", exception.Message);
                return Json(ret);
            }

            return Json(ret);
        }

        #endregion 
        #region 点菜实时列表 

        public ActionResult Operate(int id)
        {
            ViewBag.Id = id;
            return View();
        }

        /// <summary>
        /// 点菜实时列表
        /// </summary>
        /// <returns></returns>
        public ActionResult OrderDish() {

            return View();
        }

        [HttpPost]
        public ActionResult _OrderDishList()
        {
            var modelList = _dineService.QueryCookDishList();
            
            #region 测试数据

            #if DEBUG

            modelList = new List<UIModel.Dine.CookDishViewModel>(){
                new UIModel.Dine.CookDishViewModel(){
                    Id=1,
                    DishId=2,
                    DishName="菜名",
                    DishState=3,
                    OrderId=1111,
                    DineTable="5桌",
                    CookChef="1号大厨",
                    OrderConfirmTime=DateTime.Now,
                    CookWeight=100,
                    PressWeight=10,
                    OtherWeight=0
                }
            };

            #endif

            #endregion

            return View(modelList);
        }

        /// <summary>
        /// 加速催菜
        /// </summary>
        /// <param name="dishId"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SpeedDish(String id)
        {
            var ret = new JsonReturnMessages();
            ret.IsSuccess = false;
            ret.Msg = "未知错误";
            try
            {
                Int32 id_int = 0;
                if (Int32.TryParse(id, out id_int))
                {
                    Boolean result = _dineService.SpeedOrderDish(id_int);
                    if (result)
                    {
                        ret.IsSuccess = true;
                        ret.Msg = "催菜成功";
                    }
                    else
                    {
                        ret.IsSuccess = false;
                        ret.Msg = "催菜失败";
                    }
                }
                else {
                    throw new Exception(String.Format("无效的ID：{0}", id));
                }
            }
            catch (Exception exception)
            {
                ret.IsSuccess = false;
                ret.Msg = String.Format("操作失败！{0}", exception.Message);
                return Json(ret);
            }

            return Json(ret);

        }

        #endregion  
        #region 测试 
        public ActionResult Test()
        {
            return View();
        } 
        #endregion


        #region 电话预定

        public ActionResult AddOrder()
        {
            var model = new D_Order
                {
                    H_Id = CurrentUser.HotelId,
                    CreateUser = CurrentUser.H_UserName,
                    OrderTime = DateTime.Now
                };
            //ViewBag.Seat = new RBS.Core.BLL.Hotel.H_Hotel_Seat().GetModelList(" hotelid=" + CurrentUser.HotelId + " and Status=0 order by  Category asc , Numbers asc");

            return View(model);
        }
        [HttpPost]
        public ActionResult AddOrder(FormCollection collection)
        {
            var _OrderTime = collection["OrderTime"].ToDateTime();
            var model = new D_Order
                {
                    OrderTime = _OrderTime,
                    ReserveDate = _OrderTime.ToString("yyyy年MM月dd天"),
                    ReserveTime = _OrderTime.ToString("HH时mm分"),
                    OrderChannel = "电话",
                    ContactUser = collection["ContactUser"],
                    ContactMobile = collection["ContactMobile"],
                    PayTime = _OrderTime,
                    DineNum = Convert.ToInt32(collection["DineNum"]),
                    H_Id = CurrentUser.HotelId,
                    HotelName = new RBS.Core.BLL.Hotel.H_Hotels().GetModelByCache(CurrentUser.HotelId).H_Name,
                    DineTable = Convert.ToInt32(collection["seat"].Split('|')[0]),
                    Dinecondition = collection["seat"].Split('|')[1],
                    U_Id = -1,
                    CreateTime = DateTime.Now,
                    CreateUser = CurrentUser.H_UserName,
                    LastModifyDate = DateTime.Now,
                    LastModifyUser = CurrentUser.H_UserName,
                    OrderState = 2
                };

               var flag= new RBS.Core.BLL.D_Order().Add(model);

            if (flag > 0)
            {
                return RedirectToAction("OrderList");
            }
            else
            {
                return View();
            }


            return View();
        }
        public JsonResult GetSeatStatus(string time)
        {
            var ret = new JsonReturnMessages();
            var time1 = Convert.ToDateTime(time).AddHours(-3);
            var time2 = Convert.ToDateTime(time).AddHours(3);
            ret.Data = new RBS.Core.BLL.Hotel.H_Hotel_Seat().GetSeatList(CurrentUser.HotelId, time1, time2);
            ret.IsSuccess = true;
            return Json(ret, JsonRequestBehavior.AllowGet);
        }

        #endregion
    }
}
